package com.zues.thread.method.interrupt;

import com.zues.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName Demo1
 * @Description 测试线程打断方法
 * interrupt()打断这个线程，异常处理机制
 * sleep、wait、join 方法都会让线程进入阻塞状态，线程在阻塞状态时打断线程会清空打断状态（false）
 * @Author zeus
 * @Date 2/28/2025 5:10 下午
 * @Version 1.0
 **/
@Slf4j(topic = "c.Demo1")
public class Demo1 {

    public static void main(String[] args) {
        // 示例1：打断阻塞中的线程
        Thread t1 = new Thread(() -> {
            ThreadUtil.sleep(5);
            boolean interrupted = Thread.currentThread().isInterrupted();
            log.info("interrupted:{}", interrupted);
        }, "t1");

        // 示例2：中断运行中的线程
        Thread t2 = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                // 正常执行任务
//                log.debug("运行中...");
            }
            log.debug("通过中断标志退出 {}", Thread.currentThread().isInterrupted());
        }, "t2");

        t1.start();
        t2.start();
        ThreadUtil.sleep(1);
        t1.interrupt();
        t2.interrupt();
        log.info(" 打断状态: {}", t1.isInterrupted());// 打断状态: {}false
        log.info(" 打断状态: {}", t2.isInterrupted());// 打断状态: {}false
    }

}
